package com.xsjl.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xsjl.common.entity.PageResult;
import com.xsjl.common.entity.Result;
import com.xsjl.common.entity.StatusCode;
import com.xsjl.common.utils.JwtUtil;
import com.xsjl.user.pojo.User;
import com.xsjl.user.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * user控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/updateFans/{userid}/{count}")
    public void updateFans(@PathVariable String userid, @PathVariable int count) {
        userService.updateFanCount(userid, count);
    }

    @GetMapping("/updateFollows/{userid}/{count}")
    public void updateFollows(@PathVariable String userid, @PathVariable int count) {
        userService.updateFollowCount(userid, count);
    }

    @DeleteMapping(value = "/{id}")
    public Result delete(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("admin_claims");
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR, "权限不足");
        }
        if (!"admin".equals(claims.get("roles"))) {
            return new Result(false, StatusCode.ACCESSERROR, "权限不足");
        }
        userService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }


    @PostMapping(value = "/login")
    public Result login(@RequestBody User user) {
        User loginUser = userService.findByUsernameAndPass(user.getUsername(), user.getPassword());
        if (loginUser == null) {
            return new Result(false, StatusCode.LOGINERROR, "账号或密码输入错误,请重新输入!");
        }
        String token = jwtUtil.createJWT(loginUser.getId(), loginUser.getUsername(), "user");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("name", loginUser.getUsername());
        map.put("avatar", loginUser.getAvatar());
        return new Result(true, StatusCode.OK, "登录成功", map);
    }

    @PostMapping(value = "/sendsms/{email}")
    public Result sendsms(@PathVariable String email) {
        // 判断邮箱是否已经存在
        Map<String, Object> map = new HashMap<>();
        map.put("email", email);
        List<User> search = userService.findSearch(map);
        if (search.size() != 0) {
            return new Result(false, StatusCode.REPERROR, "该邮箱已经注册过账号！");
        }

        // 判断用户是否再次注册
        Object o = redisTemplate.opsForValue().get("smscode_" + email);
        if (o != null) {
            return new Result(false, StatusCode.REPERROR, "请不要重复注册");
        }
        userService.sendSms(email);
        return new Result(true, StatusCode.OK, "send success");
    }


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotal(), pageList.getRecords()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param user
     */
    @RequestMapping(value = "/register/{code}", method = RequestMethod.POST)
    public Result add(@PathVariable String code, @RequestBody User user) {
        String smscode = (String) redisTemplate.opsForValue().get("smscode_" + user.getEmail());
        if (!code.equals(smscode)) {
            return new Result(false, StatusCode.LOGINERROR, "验证码输入错误或验证码已过期,请重新输入");
        }

        //移除验证码
        redisTemplate.delete("smscode_" + user.getEmail());
        user.setFollowcount(0);//关注数
        user.setFanscount(0);//粉丝数
        user.setOnline(0L);//在线时长
        user.setLastdate(new Date());//最后登陆日期
        user.setAvatar("http://qiniu.qiangly.top/20210316220031.jpg");
        userService.add(user);
        return new Result(true, StatusCode.OK, "注册成功");
    }

    /**
     * 修改
     *
     * @param user
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }



}
